package com.huitongmaoyi.ai.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据库工具类（线程安全改进）
 */
public class DBUtil {
    // 数据库连接信息（请替换为实际配置）
    public static final String URL = "jdbc:mysql://localhost:3306/huitongmaoyi_ai?useSSL=false&serverTimezone=UTC";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "123456";

    // 线程本地存储：每个线程持有独立的数据库连接
    private static final ThreadLocal<Connection> connectionHolder = new ThreadLocal<>();

    /**
     * 获取当前线程的数据库连接
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = connectionHolder.get();
        if (conn == null || conn.isClosed()) {
            // 新建连接并绑定到当前线程
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            connectionHolder.set(conn);
        }
        return conn;
    }

    /**
     * 关闭当前线程的数据库连接
     */
    public static void closeConnection() {
        Connection conn = connectionHolder.get();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.err.println("数据库连接关闭失败：" + e.getMessage());
            }
            connectionHolder.remove(); // 移除线程绑定
        }
    }
}